package com.xj.fileremove.service;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class fileService {
    private static String path = "F:\\BaiduNetdiskDownload\\2020期录播视频\\04.微服务架构";

    private static String toPath = "E:\\java视频\\100037";

    public static void main(String[] args) throws IOException {
        findTargetFile(path);
//        String yFile = "F:\\BaiduNetdiskDownload\\2020期录播视频\\04.微服务架构\\03. Spring Cloud Alibaba\\3.9 Nacos 的初步认识和基本应用\\Nacos 的初步认识和基本应用.zip";
//        String toFile = "F:\\BaiduNetdiskDownload\\2020期录播视频\\04.微服务架构\\03. Spring Cloud Alibaba\\3.9 Nacos 的初步认识和基本应用";
//        unZip(new File(yFile), toFile);
    }
    // 找到指定的文件夹
    public static void findTargetFile(String targetFile) throws IOException {
        File file = new File(targetFile);
        if (file.isDirectory()) {
            String[] list = file.list();
            System.out.println(JSON.toJSONString(list));
            System.out.println("path: " + file.getPath());
            assert list != null;
            if (list.length > 0) {
                for (String fileName : list) {
                    findTargetFile(targetFile + "\\" + fileName);
                }
            }
        } else {
            if (file.getName().endsWith(".zip")) {
                String path = file.getParentFile().getPath();
                String name = file.getName().split("\\.")[0];
                String unzipFile = path + "\\" + name;
//                File newFile = new File(file.);

                try {
//                    if (!newFile.exists()) {
//                        newFile.
//                    }
                    unZip(file, unzipFile);
                } catch (Exception e) {
                    System.err.println(path);
                    System.err.println(name);
                    System.out.println(unzipFile);
                    e.printStackTrace();
                    return;
                }

                copyFile(unzipFile);
            }
        }
    }

    public static void copyFile(String fileName) throws IOException {
        File file = new File(fileName);
        if (file.isDirectory()) {
            String[] list = file.list();
            for (String f : list) {
                copyFile(fileName + "\\" + f);
            }
        } else {
            if (file.getName().endsWith(".gpv")) {
                copy(fileName, file.getPath(), toPath);
            }
        }
    }

    /**
     * 解压文件
     * @param srcFile
     * @param destDirPath
     * @throws RuntimeException
     */
    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    fos.write(is.available());
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }

            }

            long end = System.currentTimeMillis();

            System.out.println("解压完成，耗时：" + (end - start) + " ms");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("unzip error from ZipUtils", e);

        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();

                } catch (IOException e) {
                    e.printStackTrace();

                }

            }

        }
    }


    /**
     * 复制路径
     * @param filename 文件名
     * @param oldpath 原路径
     * @param newpath 新路径
     * @throws IOException
     */
    private static void copy(String filename, String oldpath, String newpath) throws IOException {
        File oldpaths = new File(oldpath + "\\" + filename);
        File newpaths = new File(newpath + "\\" + filename);
        if (!newpaths.exists()) {
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        } else {
            newpaths.delete();
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        }
    }

        // 遍历所有文件
    // 解压压缩包
    // 遍历解压后的文件，找到目标文件
    // 将目标文件移到指定文件夹
}
